#include <P2PBrokerI.h>

P2PBrokerI::P2PBrokerI(string fileName, 
		       ::Yafridng::FileStorePrx& myFileStore,
		       ::Yafridng::Pieces& pieces,
		       Controller *c) : _fileName(fileName),
					_num(1000*1024),
					_myFileStore(myFileStore),
					_pieces(pieces),
					_control(c)
{
}

void P2PBrokerI::notifyPiece(const ::Ice::Int piece,
			     const ::Yafridng::FileStorePrx& fileSt,
			     const ::Ice::Current&)
{
  Lock sync(*this);
  PieceInfo p;
  p.piece = piece;
  p.fileStore = fileSt;
  availablePieces.push_back(p);
}

::Yafridng::FilePrx P2PBrokerI::getPieceKeeper(const Ice::Int piece,
					       /*const ::std::string& nodeId,*/
					       const ::Ice::Current& c)
{
  Lock sync(*this);
  //_control->incP2P(nodeId);
  //cout << "Peticion: " << nodeId << endl;
  for(int i = 0; i < availablePieces.size(); i++)
    {
      if(availablePieces.at(i).piece == piece)
	{
	  //Getting path in the server. Temporary Solution
	  int startIndex = _fileName.rfind("/", _fileName.size());
	  string fileName = _fileName.substr(startIndex + 1, _fileName.size());
	  //Path in the server
	  return availablePieces.at(i).fileStore->read(fileName, 
						       _num, 
						       _pieces.at(piece).offset, 
						       _pieces.at(piece).pieceSize);
	}
    }
  cout << "Devolviendo mi fileStore" << endl;
  return _myFileStore->read(_fileName, 
			    _num, 
			    _pieces.at(piece).offset, 
			    _pieces.at(piece).pieceSize);
}
